package com.itheima.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.dto.OrderInfoDto;
import com.itheima.entity.BeanConv;
import com.itheima.mapper.OrderMapper;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.service.MemberService;
import com.itheima.service.OrderService;
import com.itheima.service.OrderSettingService;
import com.itheima.utils.DateUtil;
import com.itheima.utils.DateUtils;
import com.itheima.utils.SnowflakeIdWorker;
import com.itheima.vo.OrderInfoVo;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author ：yuanjian
 * @date ：Created in 2020/11/17 17:01
 * @description：
 */

@Service
//@Transactional
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {


    @Reference
    private OrderSettingService orderSettingService;

    @Resource
    private MemberService memberService;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;


    @Override
    @Transactional
    public Object addOrder(OrderInfoDto orderInfoDto) {
        /*try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/
        //1.短信验证码校验
        String smsCode = (String) redisTemplate.opsForValue().get("sms:code:" + orderInfoDto.getTelephone());
        if (smsCode == null) throw new RuntimeException("没有发送短信验证码或者短信验证码已过期，请重新发送！");
        if (!smsCode.equals(orderInfoDto.getSmsCode())) throw new RuntimeException("验证码输入错误");

        //2.当前日期是否可以预约
        //  select  count(0) from t_ordersetting where  orderdate = ? and number > 已经预约数
        int count = orderSettingService.isOrderOkByOrderDate(DateUtil.formatDate(orderInfoDto.getOrderDate()));
        if (count == 0) throw new RuntimeException("当前日期预约数已满");

        //3.判断是否重复预约
        //  当天没有预约满 。。。  当前用户是否是新还是老用户
        Member member = memberService.findMemeberByTelephone(orderInfoDto.getTelephone());
        if (member != null) {
            //    老会员    才会有重复预约的问题 ？   根据 预约日期和套餐id 和会员id  三者条件并列  存储结果  ： 预约过了！
            //  select count(1) from t_order where member_id = ? and orderdate = ? and setmeal_id = ?
            int i = baseMapper.hasOrderByOrderDateAndSetmealIdAndMemberId(
                    DateUtil.formatDate(orderInfoDto.getOrderDate()),
                    orderInfoDto.getSetmealId(), member.getId());
            if (i > 0) {
                throw new RuntimeException("不可重复预约");
            }

        }
        //4.预约设置预约数修改
        orderSettingService.updateReservationsByOrderDate(DateUtil.formatDate(orderInfoDto.getOrderDate()));
        //5.会员信息维护
        if (member == null) {
            member = new Member();
            member.setRegTime(new Date());
        }
        member.setTelephone(orderInfoDto.getTelephone());
        member.setName(orderInfoDto.getName());
        member.setSex(orderInfoDto.getSex());
        member.setIdCard(orderInfoDto.getIdCard());
        Long memberId = memberService.saveMember(member);

        //6.预约订单
        Order order = new Order();
        //雪花算法生成唯一ID(20位长度的long类型数据)
        order.setOrderNo(String.valueOf(SnowflakeIdWorker.getInstance().nextId()));
        order.setSetmealId(orderInfoDto.getSetmealId());
        order.setMemberId(memberId);
        order.setOrderDate(orderInfoDto.getOrderDate());
        order.setPayStatus(0);
        order.setOrderType(orderInfoDto.getOrderType());
        this.save(order);

        return order.getId();
    }

    @Override
    public OrderInfoVo findOrderInfo(Long orderId) {
        OrderInfoVo orderInfo = baseMapper.findOrderInfo(orderId);
        return orderInfo;
    }

    @Override
    public void updateStatus(String orderNo) {

        baseMapper.updateStatus(orderNo);
    }


    @Transactional
    @Override
    public String isPay(String orderNo) {
        return baseMapper.isPay(orderNo);
    }

    @Override
    public Integer selectPayStatusById(Long orderId) {
        Integer payStatus = baseMapper.selectPayStatusById(orderId);
        return payStatus;
    }

    @Override
    public void deleteOrderById(long id) {
        baseMapper.deleteById(id);
    }

    @Override
    public Map findsetmeal() {
        Map setmealMap = new HashMap();
        List<Map> mapList = this.baseMapper.findsetmeal();
        List<String> list = new ArrayList<>();
        for (Map map : mapList) {
            list.add((String) map.get("name"));
        }
        setmealMap.put("setmealNames",list);
        setmealMap.put("setmealCounts",mapList);
        return setmealMap;
    }



}
